package com.hu.bgp.server;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import com.hu.bgp.framework.GameState;

public class GameInstanceCollection
{
	private Hashtable<String, Hashtable<String, GameInstance>> index = new Hashtable<String, Hashtable<String, GameInstance>>();
	private Hashtable<String, GameInstance> initializingGames = new Hashtable<String, GameInstance>();
	private Hashtable<String, GameInstance> waitingGames = new Hashtable<String, GameInstance>();
	private Hashtable<String, GameInstance> runningGames = new Hashtable<String, GameInstance>();
	private ArrayList<GameInstance> allInstances = new ArrayList<GameInstance>();

	public void put(GameInstance gameInstance, GameState state)
	{
		Hashtable<String, GameInstance> collection = getStateCollection(state);

		collection.put(gameInstance.getUuidString(), gameInstance);
		index.put(gameInstance.getUuidString(), collection);
		allInstances.add(gameInstance);
	}

	public GameInstance get(String guid)
	{
		return index.get(guid).get(guid);
	}

	public void remove(String uuid)
	{
		GameInstance instance = index.get(uuid).remove(uuid);
		index.remove(uuid);
		allInstances.remove(instance);
	}

	public void changeState(String uuid, GameState newState)
	{
		GameInstance instance = index.get(uuid).remove(uuid);
		index.remove(uuid);
		put(instance, newState);
	}

	public List<GameInstance> getAllInstances()
	{
		return allInstances;
	}

	private Hashtable<String, GameInstance> getStateCollection(GameState state)
	{
		switch (state)
		{
			case INITIALIZING:
				return initializingGames;
			case WAITING_FOR_PLAYERS:
				return waitingGames;
			case RUNNING:
				return runningGames;
			default:
				return null;
		}
	}

	public int countPlayers()
	{
		int result = 0;
		for (GameInstance instance : allInstances)
		{
			if (instance.getGameContext().getState() == GameState.RUNNING)
			{
				result += instance.getGameContext().getPlayers().size();
			}
		}
		return result;
	}
}
